package org.viettan.android.main.intents;

import java.util.List;

import org.viettan.android.main.R;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Parcelable;

import com.google.common.collect.Lists;

/**
 * Provides utility methods to create/share and send intents.
 */
public class IntentUtility {

    /**
     * Starts the web browser and navigates to the given URL.
     *
     * @param context
     *            the context from which the intent is sent
     * @param uri
     *            the full URL of the web page to load
     */
    public void sendBrowseIntent(Context context, Uri uri) {
	Intent browserIntent = new Intent(Intent.ACTION_VIEW, uri);
	context.startActivity(browserIntent);
    }

    /**
     * Shares some subject and text to another application. For instance, this can be used to share
     * articles to Facebook/Google+ or whatever application that is installed on the phone that can
     * handle text. Most applications like Facebook or Google+ will look for a URL somewhere in the
     * text.
     *
     * @param context
     *            the context from which the share originates
     * @param subject
     *            the subject line to share
     * @param text
     *            the full text to share. Consider adding a URL somewhere in here for applications
     *            to parse and load.
     */
    public void sendShareIntent(Context context, String subject, String text) {
	List<Intent> targetedIntents = Lists.newArrayList();
	Intent shareIntentForQuerying = new Intent(android.content.Intent.ACTION_SEND);
	shareIntentForQuerying.setType("text/plain");

	// gets the list of applications that can share
	// See http://stackoverflow.com/questions/2077008/android-intent-for-twitter-application
	List<ResolveInfo> resInfo = context.getPackageManager().queryIntentActivities(
		shareIntentForQuerying, 0);
	for (ResolveInfo info : resInfo) {
	    Intent targetedIntent = new Intent(android.content.Intent.ACTION_SEND);
	    targetedIntent.setType("text/plain");
	    targetedIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
	    targetedIntent.putExtra(Intent.EXTRA_TEXT, text);
	    targetedIntent.setPackage(info.activityInfo.packageName);
	    targetedIntents.add(targetedIntent);
	}

	// show share intent
	Intent chooserIntent = Intent.createChooser(targetedIntents.remove(0), context
		.getResources().getString(R.string.menu_share_url));
	chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
		targetedIntents.toArray(new Parcelable[] {}));
	context.startActivity(chooserIntent);
    }
}
